<script setup>
import { ref } from 'vue';

import { Lock, Message, Key, Stopwatch } from '@element-plus/icons-vue';
import {
  appUserForgetPasswdVerifyCodeMailService,
  appUserResetPasswdService
} from '@/apis/appuser';

const fpFormDefault = {
  email: '',
  newPassword: ''
};

const fpFormModel = ref({
  ...fpFormDefault
});

const fpForm = ref();

// 忘记密码验证码相关
const fpVerifyCodeBtn = ref({
  disabled: false,
  text: '获取验证码',
  loading: false
});
const onfpVerifyCodeBtnClick = async () => {
  await fpForm.value.validateField('email');

  // （网络请求）loading 开启
  fpVerifyCodeBtn.value.loading = true;
  let reqData = {
    email: fpFormModel.value.email
  };
  await appUserForgetPasswdVerifyCodeMailService(reqData)
    .then((res) => {
      ElMessage.success('请求验证码成功');
      // （网络请求）loading 关闭
      fpVerifyCodeBtn.value.loading = false;

      // （防止重复点击）禁用开启
      fpVerifyCodeBtn.value.disabled = true;

      let remainingSeconds = res.data;
      fpVerifyCodeBtn.value.text = `（${remainingSeconds}）`;
      var handler = setInterval(() => {
        if (remainingSeconds >= 1) {
          fpVerifyCodeBtn.value.text = `（${--remainingSeconds}）`;
          return;
        }

        // （防止重复点击）禁用关闭
        fpVerifyCodeBtn.value.disabled = false;
        fpVerifyCodeBtn.value.text = '再次获取';
        clearInterval(handler);
      }, 1000);
    })
    // 异常情况
    .catch(() => {
      // （网络请求）loading 关闭
      fpVerifyCodeBtn.value.loading = false;
    });
};

const doResetPasswd = async () => {
  await fpForm.value.validate();

  let res = await appUserResetPasswdService(fpFormModel.value);
  ElMessage.success(res.msg);
  finishForgetPasswd();
};

const emits = defineEmits(['finishForgetPasswd']);
const finishForgetPasswd = () => {
  emits('finishForgetPasswd');
};

const rules = {
  email: [
    {
      type: 'email',
      required: true,
      message: '请输入正确的电子邮箱',
      trigger: 'blur'
    }
  ],
  newPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15 位的非空字符',
      trigger: 'blur'
    }
  ],
  rePassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是 6-15 位的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== fpFormModel.value.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback(); // 校验成功后也需要 callback
        }
      },
      trigger: 'blur'
    }
  ]
};

const resetForgetPasswd = () => {
  fpFormModel.value = ref({
    ...fpFormDefault
  });
};

defineExpose({
  resetForgetPasswd
});
</script>

<template>
  <!-- 注册相关表单 -->
  <el-form
    :model="fpFormModel"
    :rules="rules"
    ref="fpForm"
    size="large"
    autocomplete="off"
  >
    <el-form-item>
      <h1>忘记密码</h1>
    </el-form-item>
    <el-form-item prop="email">
      <el-input
        v-model="fpFormModel.email"
        :prefix-icon="Message"
        placeholder="请输入邮箱地址"
      ></el-input>
    </el-form-item>
    <el-form-item prop="verifyCode" class="verify-code-container">
      <el-input
        v-model="fpFormModel.verifyCode"
        :prefix-icon="Key"
        placeholder="请输入收到的验证码"
      ></el-input>
      <el-button
        class="verify-code-btn"
        type="primary"
        :disabled="fpVerifyCodeBtn.disabled"
        :loading="fpVerifyCodeBtn.loading"
        :loading-icon="Stopwatch"
        @click="onfpVerifyCodeBtnClick"
      >
        {{ fpVerifyCodeBtn.text }}
      </el-button>
    </el-form-item>
    <el-form-item prop="newPassword">
      <el-input
        v-model="fpFormModel.newPassword"
        :prefix-icon="Lock"
        type="password"
        show-password
        placeholder="请输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item prop="rePassword">
      <el-input
        v-model="fpFormModel.rePassword"
        :prefix-icon="Lock"
        type="password"
        show-password
        placeholder="请再次输入密码"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        @click="doResetPasswd"
        class="button"
        type="primary"
        auto-insert-space
      >
        确定
      </el-button>
    </el-form-item>
    <el-form-item class="flex">
      <el-link type="info" :underline="false" @click="finishForgetPasswd()">
        ← 返回
      </el-link>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
.button {
  width: 100%;
}

.verify-code-container :deep(.el-form-item__content) {
  flex-wrap: nowrap;
  justify-content: space-between;
}

.verify-code-btn {
  flex-basis: 150px;
}
</style>
